package cn.ddiancan.xddcloud.psc.oss.service;

import cn.ddiancan.xddcloud.common.entity.CommonResult;
import cn.ddiancan.xddcloud.psc.oss.config.XddcloudSmsProperties;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class XddcloudSmsService {

    private final XddcloudSmsProperties xddcloudSmsProperties;

    /**
     * 发送短信
     *
     * @param phoneNumbers  手机号
     * @param templateParam 短信模板参数,例如{"code":"123456"}
     * @return CommonResult
     */
    public CommonResult<?> sendSms(String phoneNumbers, JSONObject templateParam) {
        return sendSms(phoneNumbers, xddcloudSmsProperties.getSign(), xddcloudSmsProperties.getTemplateCode(),
            templateParam, xddcloudSmsProperties.getRegionId(), xddcloudSmsProperties.getAccessKeyId(),
            xddcloudSmsProperties.getAccessKeySecret(), xddcloudSmsProperties.getDomain());
    }

    /**
     * 发送短信
     *
     * @param phoneNumbers    手机号
     * @param signName        签名
     * @param templateCode    模板code
     * @param templateParam   模板参数
     * @param regionId        区域
     * @param accessKeyId     accessKeyId
     * @param accessKeySecret accessKeySecret
     * @param domain          domain
     * @return CommonResult
     */
    public CommonResult<?> sendSms(String phoneNumbers, String signName, String templateCode, JSONObject templateParam,
        String regionId, String accessKeyId, String accessKeySecret, String domain) {
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(domain);
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("PhoneNumbers", phoneNumbers);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        if (templateParam != null) {
            request.putQueryParameter("TemplateParam", JSON.toJSONString(templateParam));
        }
        String errorMessage = null;
        try {
            CommonResponse sendSmsResponse = acsClient.getCommonResponse(request);
            if (sendSmsResponse.getHttpStatus() == 200) {
                JSONObject result = JSONObject.parseObject(sendSmsResponse.getData());
                if ("OK".equals(result.getString("Code"))) {
                    return CommonResult.success();
                } else {
                    return CommonResult.failed("发送验证码失败，请联系管理员");
                }
            } else {
                return CommonResult.failed(sendSmsResponse.getData());
            }
        } catch (ServerException serverException) {
            log.info("ServerException:{}", serverException.getErrMsg());
            errorMessage = serverException.getErrMsg();
        } catch (ClientException clientException) {
            log.info("ClientException:{}", clientException.getErrMsg());
            errorMessage = clientException.getErrMsg();
        }

        return CommonResult.failed(errorMessage);
    }

}
